import { Effect } from 'dva';
import { loadSsqData } from '@/services/ssq';
import { Reducer } from 'redux';

export interface StateType {
  code: string,
  date: string,
  red1: number,
  red2: number,
  red3: number,
  red4: number,
  red5: number,
  red6: number,
  blue: number,
}

interface ModelType {
  namespace: string;
  state: StateType[];
  effects: {
    load: Effect;
  };
  reducers: {
    updateState: Reducer<StateType[]>;
  };
}


const Model: ModelType = {
  namespace: 'ssqDataList',
  state: [],
  effects: {
    * load({ payload }, { call, put }) {
      const response = yield call(loadSsqData, payload);
      if (response.state === 0) {
        const data = response.result.map((item: any) => {
          const reds = item.red.split(',').map((num: string) => Number(num));
          return {
            code: item.code,
            date: item.date,
            red1: reds[0],
            red2: reds[1],
            red3: reds[2],
            red4: reds[3],
            red5: reds[4],
            red6: reds[5],
            blue: Number(item.blue),
          };
        });
        yield put({
          type: 'updateState',
          payload: data,
        });
      }
    },
  },
  reducers: {
    updateState(state, { payload }) {
      return payload;
    },
  },
};

export default Model;
